﻿# -*- coding: utf-8 -*-
import xlrd
import xlwt
from sshclient import SSHProxy
import re

workbook = xlwt.Workbook(encoding='utf-8')
logs = workbook.add_sheet('logs')
ips = xlrd.open_workbook('ips-run.xls')
ipset = ips.sheet_by_index(0)  # 能过序号来获取
ips = ipset.col_values(0)  # 获取第1列内容

userlist = [
    {'username': 'root', 'pwd': 'Password!'},
]
# cmd = "cat /etc/redhat-release"
# cmd = "ps -ef|grep titanagent"
cmd = "ps -ef|grep titanagent"
# cmd = "curl -s -L 'http://10.126.115.39/agent/download?k=8244f3c7a3693e5ee58db375223f8a0870a9fe5b&group=8&protocol=0' | bash"
row = 0
for host in ips:
    print(host)
    for user in userlist:
        print(row, host, user)
        try:
            with SSHProxy(host, int(22), user['username'], user['pwd']) as ssh:
                result = ssh.command(cmd)
                # print(result['code'])
                # print(result['result'])
                # print(host, user, result)
                row = row + 1
                logs.write(row, 0, host)
                logs.write(row, 1, user['username'])
                logs.write(row, 2, user['pwd'])
                logs.write(row, 3, str(result['code']))
                logs.write(row, 4, str(result['result']))
                # result = str(result['result'])
                workbook.save('logs.xls')
                # # print(result)
                # agent = re.findall('titanagent', result)
                # if agent:
                #     logs.write(row, 4, 'install')
                # else:
                #     logs.write(row, 4, 'None')
        except Exception as e:
            # print(host, user)
            continue
